<?php
namespace app\common\lib\redis;

class Predis {
	private static $_instance = null;
	private $redis = null;

	final private function __construct(){
		$this->redis = new \Redis();
		$this->redis->connect(config('redis.host'),config('redis.port'),3);
		$this->redis->auth(config('redis.password'));
	}

	private function __clone(){

	}

	public static function getInstance(){
		if (!(self::$_instance instanceof self)){
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	public function set($key, $value, $time = 0){
		if(!$key){
			return '';
		}
		$value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
		if(!$time){
			return $this->redis->set($key, $value);
		}else{
			return $this->redis->setex($key, $time, $value);
		}
	}

	public function get($key){
		if(!$key){
			return '';
		}
		$value =  $this->redis->get($key);
		$jsonData = json_decode($value, true);
        // 检测是否为JSON数据 true 返回JSON解析数组, false返回源数据 byron sampson<xiaobo.sun@qq.com>
		return (null === $jsonData) ? $value : $jsonData;
	}



	public function Sadd($key, $value){
		if(!$key){
			return '';
		}
		$value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
		return $this->redis->Sadd($key, $value);
	}
	public function Srem($key, $value){
		if(!$key){
			return '';
		}
		$value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
		return $this->redis->Srem($key, $value);
	}


	public function __call($name, $param){

		switch(count($param)){
			case 2:
			list($key,$value) = $param;
			$value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
			$res = $this->redis->$name($key,$value);
			break;
			default:
			$value = $this->redis->$name($param[0]);
			$jsonData = json_decode($value, true);
			$res =  (null === $jsonData) ? $value : $jsonData;
			break;
		}
		return $res;
	}
}
